package com.example.choupaiapp.main.activity.home;

import android.Manifest;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.example.choupaiapp.R;
import com.example.choupaiapp.common.ui.activity.CommonActivity;
import com.example.choupaiapp.common.util.Utils;
import com.example.choupaiapp.main.util.LocationUtil;
import com.example.choupaiapp.main.view.indexsidebar.City;
import com.example.choupaiapp.main.view.indexsidebar.CityAdapter;
import com.example.choupaiapp.main.view.indexsidebar.IndexSideBar;
import com.example.choupaiapp.main.view.indexsidebar.LetterComparator;
import com.example.choupaiapp.main.view.indexsidebar.PinnedHeaderDecoration;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by ASUS on 2019/11/4.
 */

public class LocationCityActivity extends CommonActivity implements AMapLocationListener {

    @BindView(R.id.right_tv)
    TextView rightTv;
    @BindView(R.id.location_tv)
    TextView locationTv;
    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R.id.side_bar)
    IndexSideBar side_bar;
    private String city;
    private CityAdapter adapter;
    private AMapLocation mAMapLocation;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_location_city);
    }

    @Override
    protected void initView() {
        setTitle("选择城市");
        side_bar.setVisibility(View.VISIBLE);

        EventBus.getDefault().register(this);

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            city = bundle.getString("city");
            locationTv.setText(city);
        } else {
            locationTv.setText("定位失败");
        }

        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));

        final PinnedHeaderDecoration decoration = new PinnedHeaderDecoration();
        decoration.registerTypePinnedHeader(1, (parent, adapterPosition) -> true);

        mRecyclerView.addItemDecoration(decoration);

        Type listType = new TypeToken<ArrayList<City>>() {
        }.getType();
        Gson gson = new Gson();
        final List<City> list = gson.fromJson(City.DATA, listType);
        Collections.sort(list, new LetterComparator());

        adapter = new CityAdapter(context, list);
        mRecyclerView.setAdapter(adapter);

        adapter.addOnItemClickListener((vh, position) -> {
            EventBus.getDefault().post("city:" + adapter.getItem(position).name);
            finishActivity();
        });

        side_bar.setOnTouchLetterChangeListener(letter -> {
            int pos = adapter.getLetterPosition(letter);

            if (pos != -1) {
                mRecyclerView.scrollToPosition(pos);
                LinearLayoutManager mLayoutManager =
                        (LinearLayoutManager) mRecyclerView.getLayoutManager();
                mLayoutManager.scrollToPositionWithOffset(pos, 0);
            }
        });

    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void OnMessageEvent(String event) {
        if (event.equals("finish_location_search")) {
            finishActivity();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void initData() {

    }

//    @Override
    @OnClick({R.id.search_location, R.id.refresh_location})
    public void onViewClicked(View view) {
//        super.onViewClicked(view);
        if (Utils.isDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.search_location:
                startActivity(LocationCitySearchActivity.class);
                break;
            case R.id.refresh_location:
                break;
        }
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                mAMapLocation = aMapLocation;
                //可在其中解析amapLocation获取相应内容。
//                aMapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
//                aMapLocation.getLatitude();//获取纬度
//                aMapLocation.getLongitude();//获取经度
//                aMapLocation.getAccuracy();//获取精度信息
//                aMapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
//                aMapLocation.getCountry();//国家信息
//                aMapLocation.getProvince();//省信息
//                aMapLocation.getCity();//城市信息
//                aMapLocation.getDistrict();//城区信息
//                aMapLocation.getStreet();//街道信息
//                aMapLocation.getStreetNum();//街道门牌号信息
//                aMapLocation.getCityCode();//城市编码
//                aMapLocation.getAdCode();//地区编码
//                aMapLocation.getAoiName();//获取当前定位点的AOI信息
//                aMapLocation.getBuildingId();//获取当前室内定位的建筑物Id
//                aMapLocation.getFloor();//获取当前室内定位的楼层
//                aMapLocation.getGpsAccuracyStatus();//获取GPS的当前状态
//                //获取定位时间
//                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                Date date = new Date(aMapLocation.getTime());
//                df.format(date);

                Logger.e(aMapLocation.getStreet() + "---" + aMapLocation.getStreetNum() + "---" + aMapLocation.getAoiName() + "---" + aMapLocation.getBuildingId() + "---" + aMapLocation.getFloor());

                LocationUtil.getInstance().stopLocation();//停止定位后，本地定位服务并不会被销毁

                locationTv.setText(aMapLocation.getCity());

            } else {
                //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                Logger.e("AmapError--" + "location Error, ErrCode:"
                        + aMapLocation.getErrorCode() + ", errInfo:"
                        + aMapLocation.getErrorInfo());
                showImageToas("定位失败");
                locationTv.setText("无法获取位置");
            }
        }
    }
}
